<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script>
        //其实就是改变元素的top，left(所以得用position: absolute)
        //原理：鼠标点离元素的左上角的距离是不变的(拖拽的时候)
        /*
            可以看看图片
            1，鼠标按下(onmousedown)
                鼠标与元素的距离：鼠标的横/纵(X/Y) - 元素离可视区左边界的距离(obj.offsetLeft/Top)
            2，鼠标抬起（onmouseup）
            3，鼠标移动(onmousemove)
                根据距离计算出
        */
        window.onload=function(){
            var oDiv = document.getElementById('div1');
            
            //鼠标在元素上的位置
            var disX = 0;
            var disY = 0;
            //鼠标按下
            oDiv.onmousedown=function(ev){//ev 是获取鼠标位置
                var oEvent = ev || event;
                disX = oEvent.clientX - oDiv.offsetLeft;
                disY = oEvent.clientY - oDiv.offsetTop;

                var oBox = document.createElement('div');//创建了一个div
                oBox.className = 'box';
                oBox.style.width = oDiv.offsetWidth - 2 + 'px';
                oBox.style.height = oDiv.offsetHeight - 2 + 'px';
                oBox.style.left = oDiv.offsetLeft + 'px';
                oBox.style.top = oDiv.offsetTop + 'px';
                //还需要把box加入到body中去
                document.body.appendChild(oBox);
                
                //鼠标移动(当移动时，就可以进一步的计算元素的位置(根据新的鼠标位置))
                document.onmousemove=function(ev){
                    var oEvent = ev || event;
                    var l = oEvent.clientX - disX;
                    var t = oEvent.clientY - disY;
                    if(l < 0){
                        l = 0;
                    }else if(l > document.documentElement.clientWidth - oDiv.offsetWidth){
                        l = document.documentElement.clientWidth - oDiv.offsetWidth;
                    }
                    if(t < 0){
                        t = 0;
                    }else if(t > document.documentElement.clientHeight - oDiv.offsetHeight){
                        t = document.documentElement.clientHeight - oDiv.offsetHeight;
                    }
                    oBox.style.left = l + 'px';
                    oBox.style.top = t + 'px';
                }

                document.onmouseup=function(){
                    document.onmousemove = null;
                    document.onmouseup = null;
                    
                    oDiv.style.left = oBox.offsetLeft + 'px';
                    oDiv.style.top = oBox.offsetTop + 'px';
                    document.body.removeChild(oBox);
                }
                return false;
            };
        }
    </script>
    <style>
    #div1{
        width:200px; height: 100px;background: red;position: absolute;
    }
    .box{border: 2px solid black; position: absolute;}
    </style>
</head>
<body style="margin: 0; padding: 0;">
    <div id="div1"></div>
</body>
</html>